﻿Imports Microsoft.TeamFoundation.Build.Client
Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Client
Imports System.Management.Automation

Public MustInherit Class TeamFoundationServerCmdletBase
    Inherits Cmdlet

    Protected Sub New()
    End Sub

    Private _teamFoundationServer As String

    <Parameter(Position:=0, Mandatory:=True, ValueFromPipelineByPropertyName:=True), ValidateNotNullOrEmpty()> _
    Public Property TeamFoundationServer() As String
        Get
            Return _teamFoundationServer
        End Get
        Set(ByVal value As String)
            _teamFoundationServer = value
            _buildServer = Nothing
            _workItemStore = Nothing
        End Set
    End Property

    Private _buildServer As IBuildServer
    Protected ReadOnly Property BuildServer() As IBuildServer
        Get
            If _buildServer Is Nothing Then
                _buildServer = GetTeamFoundationService(Of IBuildServer)()
            End If

            Return _buildServer
        End Get
    End Property

    Private _workItemStore As WorkItemStore
    Protected ReadOnly Property WorkItemStore() As WorkItemStore
        Get
            If _workItemStore Is Nothing Then
                _workItemStore = GetTeamFoundationService(Of WorkItemStore)()
            End If

            Return _workItemStore
        End Get
    End Property

    Protected Function GetTeamFoundationServer() As TeamFoundationServer
        Return TeamFoundationServerFactory.GetServer(TeamFoundationServer, New UICredentialsProvider())
    End Function

    Protected Function GetTeamFoundationService(Of T)() As T
        Return DirectCast(GetTeamFoundationServer().GetService(GetType(T)), T)
    End Function
End Class